package org.csu.webjpetstoreback.controller;

import jakarta.servlet.http.HttpSession;
import org.csu.webjpetstoreback.config.CommonResponse;
import org.csu.webjpetstoreback.model.Cart;
import org.csu.webjpetstoreback.model.CartItem;
import org.csu.webjpetstoreback.model.Item;
import org.csu.webjpetstoreback.model.Token;
import org.csu.webjpetstoreback.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.*;

@RestController
@SessionAttributes(names = "httpSession")
@Validated
public class CartController {

    @Autowired
    private Cart cart;

    @Autowired
    private ItemService itemService;

    @Autowired
    private Item item;


    //在这个方法里面增加购物车信息
    @PostMapping("/Carts/{itemId}")
    public CommonResponse<Token> AddItemToCartServlet2(@PathVariable("itemId")String itemId, HttpSession httpSession){
        Cart cart1 =(Cart) httpSession.getAttribute("cart");
        if (cart1 != null){
            cart = (Cart) httpSession.getAttribute("cart");
        }
        if (cart.containsItemId(itemId)){
            cart.incrementQuantityByItemId(itemId);
        }else{
            boolean isInStock = false;
            int backNumber = itemService.getInventoryByItemId(itemId).getStatus();
            if(backNumber == 200){
                isInStock = true;
            }
            item = itemService.GetItemByItemId(itemId).getData();
            cart.addItem(item,isInStock);
        }
        httpSession.removeAttribute("cart");
        httpSession.setAttribute("cart",cart);
        System.out.println("添加成功了");
        System.out.println(cart.getSubTotal());
        return CommonResponse.BackForSuccess("新增成功！！");
    }


    @GetMapping("/addItemToCart")
    public CommonResponse<Token> AddItemToCartServlet(@RequestParam("workingItemId") String itemId, HttpSession httpSession){
        System.out.println(itemId);
        Cart cart =(Cart) httpSession.getAttribute("cart");
        if (cart == null) {
            //第一次使用购物车
            cart = new Cart();
            System.out.println("test3 in AddItemToCartServlet");
        }
        if (cart.containsItemId(itemId)){
            cart.incrementQuantityByItemId(itemId);
        }else{
            boolean isInStock = false;
            int backNumber = itemService.getInventoryByItemId(itemId).getStatus();
            if(backNumber == 200){
                isInStock = true;
            }
            item = itemService.GetItemByItemId(itemId).getData();
            cart.addItem(item,isInStock);
        }
        httpSession.removeAttribute("cart");
        httpSession.setAttribute("cart",cart);
        System.out.println("添加成功了");
        return CommonResponse.BackForSuccess("新增成功！！");
    }


    //将ItemId对应的全部删掉（而不是删一个）
    @DeleteMapping("/Carts")
    public CommonResponse<Token> DeleteItemToCartServlet(@RequestParam("itemId") String itemId, HttpSession httpSession){
        cart =(Cart) httpSession.getAttribute("cart");
        item = cart.removeItemById(itemId);
        httpSession.removeAttribute("cart");
        httpSession.setAttribute("cart",cart);
        if (item == null){
            return CommonResponse.BackForError("没有该item");
        }else{
            return CommonResponse.BackForSuccess("删除成功！！");
        }

    }

    @PutMapping("/Carts")
    public CommonResponse<Token> UpdateCartJSServlet(@RequestParam("itemId") String itemId,@RequestParam("quantity") String quantity,HttpSession httpSession){
        cart =(Cart) httpSession.getAttribute("cart");
        int quan = Integer.parseInt(quantity);
        cart.setQuantityByItemId(itemId,quan);
        httpSession.setAttribute("cart",cart);
        return CommonResponse.BackForSuccess("修改成功");
    }

    @PutMapping("/Carts/1")
    public CommonResponse<Token> UpdateCartQuantityServlet(@RequestParam("itemId") String itemId,@RequestParam("quantity") String quantity,HttpSession httpSession){
        cart =(Cart) httpSession.getAttribute("cart");
        int quan = Integer.parseInt(quantity);
        Iterator<CartItem> cartItemIterator = cart.getAllCartItems();
        while (cartItemIterator.hasNext()){
            //产品数量增加
            CartItem cartItem = (CartItem) cartItemIterator.next();
            String id = cartItem.getItem().getItemId();
            try{
                cart.setQuantityByItemId(itemId,quan);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        httpSession.setAttribute("cart",cart);
        return CommonResponse.BackForSuccess("success");

    }

    @GetMapping("/Carts")
    public CommonResponse<List<Cart>> ViewCartServlet(HttpSession httpSession){
        Cart cart1 = (Cart) httpSession.getAttribute("cart");
        if (cart1 == null){
            httpSession.setAttribute("cart",cart);
        }
        List<Cart> carts = new ArrayList<>();
        carts.add(cart1);
        return CommonResponse.BackForSuccess(carts);
    }



}
